package service;

import dao.CommonDAO;
import dao.CourseDao;
import entity.Message;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MessageService {
    private CourseDao courseDao = new CourseDao();

    public List<Message> getMessageList(int page){
        return courseDao.getMessageList(page);
    }

    public int getNumberOfMessages(int status){
        return courseDao.getNumberOfMessages(status);
    }

    public void addMessage(String message){
        courseDao.addMessage(message);
    }

    private CommonDAO cd=new CommonDAO();

    public List<Message> getInfo(int status, int page, int num_every_page){
        List<Message> list=new ArrayList<>();
        String sql="select * from message where status=?"  + " limit " + (page-1)*num_every_page + "," + num_every_page;
        List<Map<String,Object>> mapList = cd.executeQuery(sql, new Object[]{status});

        for (int i=0;i<mapList.size();i++){
            Message message=new Message();
            Map<String, Object> tempMap = mapList.get(i);

            message.setContent(tempMap.get("content").toString());
            message.setCreateDate(tempMap.get("createDate").toString());
            message.setMessageId(Integer.parseInt(tempMap.get("messageId").toString()));

            list.add(message);
        }
        return list;
    }

    public int updateStatus(int id,int status){
        String sql="update message set status=? where messageId=?";
        int updateCount = cd.executeUpdate(sql, new Object[]{status, id});
        return updateCount;
    }

    public List<Message> messageDetail(Integer passageId){
        List<Message> messages=new ArrayList<>();
        String sql="select * from message where messageId=?";
        List<Map<String,Object>> mapList = cd.executeQuery(sql, new Object[]{passageId});
        for(int i=0;i<mapList.size();i++) {
            Map<String, Object> tempMap = mapList.get(i);
            Message message=new Message();
            message.setMessageId(Integer.parseInt(tempMap.get("messageId").toString()));
            message.setContent(tempMap.get("content").toString());
            message.setCreateDate(tempMap.get("createDate").toString());
            message.setStatus(Integer.parseInt(tempMap.get("status").toString()));;
            messages.add(message);
        }
        return messages;
    }

}
